﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TiEntityObject.Transport;
using TI;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;

namespace TI
{

    ///// <summary>
    ///// Операция контроллера GetHtmlDaySet упакованная в класс
    ///// </summary>
    //public class PopulateHtmlDaySetOperation
    //{
    //    private DateTime Day=DateTime .Now ;
    //    public PopulateHtmlDaySetOperation(DateTime day)
    //    {
    //        this.Day = day;
    //    }

    //    public void Run() {

    //        string dayFolder = TransportConfig.Instance.GetAttachStoreFolderPath(Day);
    //        //получить список html файлов за день
    //        List<DocumentMetaItem> htmlDaySet = GetHtmlDaySet();

    //        //получить на основе состояния каталога недостающий список DM  
    //        List<DocumentMetaItem> htmlDiff = GetHtmlDiff(htmlDaySet);

    //        //сформировать список недостающих файлов DM  
    //        CreateHtmlItems(htmlDiff);
    //    }

    //    private List<DocumentMetaItem> GetHtmlDaySet()
    //    {

    //        Helper.MongoTools t = new Helper.MongoTools();
    //        List<DocumentMetaItem> result = t.GetCollection<DocumentMetaItem>("getHtmlDaySet(" + Helper.Time.GetDateInMS(Day) + ");");
    //        return result;
    //    }



    //    private List<DocumentMetaItem> GetHtmlDiff(List<DocumentMetaItem> htmlDaySet)
    //    {
    //        return htmlDaySet;
    //    }

    //    private void CreateHtmlItems(List<DocumentMetaItem> dmList)
    //    {

    //        if (dmList.Count == 0)
    //                            return;

    //        //KillProcess("soffice.bin");

    //        //запустить обработку
    //        for (int i = 0; i < dmList.Count; i++)
    //        {
    //                CreateHtmlItem(dmList[i]);
    //                Console.WriteLine(i.ToString()); 
    //                Thread.Sleep(3000); 
    //        }
    //        Thread.Sleep(5000);
            
    //        //обновить статусы
    //        foreach (DocumentMetaItem i in dmList)
    //        {
    //            i.IsHtml = CheckHtmlExists(this.Day, i.GetFullID);
    //           Helper.MongoTools.Instance.ExecuteScript("updateDocumentMetaItem(" + i.ToString() + ")");
       
    //        }

    //    }

    //    private static  void KillProcess(string name)
    //    {
    //        foreach (Process p in System.Diagnostics.Process.GetProcessesByName("soffice"))
    //        {
    //            try
    //            {
    //                //p.Close();
    //                p.Kill();
    //                p.WaitForExit(); // possibly with a timeout
    //            }
    //            catch (Win32Exception winException)
    //            {
    //                ;
    //            }
    //            catch (InvalidOperationException invalidException)
    //            {
    //                ;
    //            }
    //        }
    //    }

    //    private static string GetHtmFileName(DateTime Day, string FullID)
    //    {
    //        string atH = TransportConfig.Instance.GetHtmlStoreFolderPath(Day);
    //        return atH + FullID + ".html";
    //    }

    //    private static string GetDocFileName(DateTime Day, string PublicFileName)
    //    {
    //        string atF = TransportConfig.Instance.GetAttachStoreFolderPath(Day);
    //        return atF + PublicFileName;
    //    }

    //    private static bool CheckHtmlExists(DateTime Day, string DocID)
    //    {
    //        string f = GetHtmFileName(Day, DocID);
    //        return File.Exists(f);
    //    }
       
    //    private void CreateHtmlItem(DocumentMetaItem item)
    //    {
    //        string mt = TransportConfig.Instance.AttchConvertorConfig.Soffice_MacroTemplate;
    //        string[] a = { @"WordToHtml", GetDocFileName(this.Day ,item.PublicFileName),GetHtmFileName(this.Day ,item.GetFullID)};
    //        string macro = string.Format(mt, a);
    //        macro = "\"" + macro + "\"";
    //        Helper.Shell.RunExe(TransportConfig.Instance.AttchConvertorConfig.Soffice_WorkFolder, @"soffice", @"-invisible " + macro, CreateHtmlItem_Exited);
    //    }

    //    private static int cnt;
    //    // Будет вызываться при завершении работы Notepad.exe
    //    private static void CreateHtmlItem_Exited(object Sender, EventArgs e)
    //    {
    //        Console.WriteLine("Счетчик " + cnt.ToString());
    //        ++cnt;
    //        // Console.WriteLine("Документ " + CurrentHtmlTransformer.Item.DocID  +"  " + CurrentHtmlTransformer.Count);
    //      // CurrentHtmlTransformer.Item.IsHtml = true;
    //      //Helper.MongoTools.Instance.ExecuteScript("updateDocumentMetaItem(" + CurrentHtmlTransformer.Item.ToString() + ")");
    //      //CurrentHtmlTransformer.IsComplete= true;
    //    }
                

    //    private static void ProcessedNextDocument(object Sender, EventArgs e)
    //    {
    //    }

    //    private DocumentMetaItem GetNotProcessedDocument()
    //    {

    //        Helper.MongoTools t = new Helper.MongoTools();
    //        DocumentMetaItem result = (DocumentMetaItem)t.GetEntity<DocumentMetaItem>("getNotHtmlDoc(" + Helper.Time.GetDateInMS(Day) + ");");
    //        return result;
    //    }

    //}

    public static  class PopulateDayHtml
    {
        static DateTime currentDay = DateTime.Now;
        static ProcessedState currentState = null;
      

      public  static void Run(DateTime day)
        {

            currentDay = day;
            currentState = new ProcessedState();
            currentState.currentDocument = GetNotProcessedDocument();
            CreateHtmlItem(currentState.currentDocument);
            do
            {   
                Thread.Sleep(100);
            } while (true);
        }

      public static void CreateHtmlItem(DocumentMetaItem item)
        {
        //    string mt = TransportConfig.Instance.AttchConvertorConfig.Soffice_MacroTemplate;
        //    string[] a = { @"WordToHtml", GetDocFileName(currentDay, item.PublicFileName), GetHtmFileName(currentDay, item.GetFullID) };
        //    string macro = string.Format(mt, a);
        //    macro = "\"" + macro + "\"";
        //    Helper.Shell.RunExe(TransportConfig.Instance.AttchConvertorConfig.Soffice_WorkFolder, @"soffice", @"-invisible " + macro, CreateHtmlItem_Exited);
            CreateHtmlItem(currentDay, item.PublicFileName, item.GetFullID, CreateHtmlItem_Exited);   
      }

      public static void CreateHtmlItem(DateTime day, string publicFileName,string FullID,  EventHandler OnCompleate)
      {
          string wMacro = @"WordToHtml";
          
          string mt = TransportConfig.Instance.AttchConvertorConfig.Soffice_MacroTemplate;
          FileInfo fi= new FileInfo (publicFileName);
          

          if (fi.Extension == ".xls")
                wMacro = "ExcelToHtml";

          string[] a = { wMacro, GetDocFileName(day, publicFileName), GetHtmFileName(day, FullID) };
          string macro = string.Format(mt, a);
          macro = "\"" + macro + "\"";
          Helper.Shell.RunExe(TransportConfig.Instance.AttchConvertorConfig.Soffice_WorkFolder, @"soffice", @"-invisible " + macro, OnCompleate);

      }
        
        private static void CreateHtmlItem_Exited(object Sender, EventArgs e)
        {
            //Console.WriteLine("Счетчик " + cnt.ToString());
            ++currentState.Count;
            Console.WriteLine("Документ " + currentState.currentDocument.DocID + "  " + currentState.Count.ToString() + " : " + (DateTime.Now-currentState.StartTime).ToString () );
            currentState.currentDocument.IsHtml = true;
            Helper.MongoTools.Instance.ExecuteScript("updateDocumentMetaItem(" + currentState.currentDocument.ToString() + ")");
            currentState.StartTime =DateTime .Now ;
            currentState.currentDocument = GetNotProcessedDocument();
            CreateHtmlItem(currentState.currentDocument);
         }


        #region Tools
        private static DocumentMetaItem GetNotProcessedDocument()
        {

            Helper.MongoTools t = new Helper.MongoTools();
            DocumentMetaItem result = (DocumentMetaItem)t.GetEntity<DocumentMetaItem>("getNotHtmlDoc(" + Helper.Time.GetDateInMS(currentDay) + ");");
            return result;
        }
        
        public  static string GetHtmFileName(DateTime Day, string FullID)
        {
            string atH = TransportConfig.Instance.GetHtmlStoreFolderPath(Day);
            return atH + FullID + ".html";
        }
        
        private static string GetDocFileName(DateTime Day, string PublicFileName)
        {
            string atF = TransportConfig.Instance.GetAttachStoreFolderPath(Day);
            return atF +@"\"+ PublicFileName;
        }

        private static bool CheckHtmlExists(DateTime Day, string DocID)
        {
            string f = GetHtmFileName(Day, DocID);
            return File.Exists(f);
        }
        #endregion
    }
    class  ProcessedState {
        public ProcessedState() { }
        public DocumentMetaItem currentDocument { get; set; }
        public DateTime StartTime { get; set; }
        public int Count { get; set; }
    }
}
